#include "SocketCommunication.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <strings.h>
#include <string.h>


SocketCommunication::SocketCommunication (unsigned short int port, char * ip)
{
  this->STATE = 0;
  this->ID = socket(AF_INET,SOCK_STREAM,0);
  if(this->ID>=0) //No hubo error.
  {
	  struct sockaddr_in caddress;
	  caddress.sin_family = AF_INET;
	  caddress.sin_port = htons(port);
	  caddress.sin_addr.s_addr = inet_addr(ip);
	  if(connect(this->ID,(struct sockaddr*)&caddress,sizeof(sockaddr))==0)
	  {
		  return;
	  }
	  else //Error al connectarse al servidor
	  {
		  throw("Error de conexion con el servidor");
	  }
  }
  else //Error al crear socket.
  {
	  throw("Error en la creacion del socket");
  }
}

SocketCommunication::SocketCommunication()
{
  this->ID = 0;
}

int SocketCommunication::SendBloq(char * data,int dataSize)
{
	return send(this->ID, data, dataSize, 0);
}

int SocketCommunication::SendBloq(envio * data,int dataSize)
{
  return send(this->ID,data,dataSize,0);
}

int SocketCommunication::ReceiveBloq(char * buffer,int bufferSize)
{
  //bzero(buffer,sizeof(buffer));
  return recv(this->ID,buffer,bufferSize,0);
}



int SocketCommunication::ReceiveBloq(envio * data, int bufferSize)
{
  //bzero(buffer,sizeof(buffer));
  return recv(this->ID,data,bufferSize,0);
}

char * SocketCommunication::GetClientIP()
{
  //this->ClientData->sin_addr.s_addr
  return inet_ntoa(this->ClientData->sin_addr);
  //return inet_ntop(AF_INET,this->ClientData->sin_addr);
}

unsigned short int SocketCommunication::GetClientPort()
{
  return ntohs(this->ClientData->sin_port);
}

SocketCommunication::~SocketCommunication ()
{
  // TODO Auto-generated destructor stub
  this->STATE = 0;
  close(this->ID);
}

